/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "ImageSequence.h"
#include <pictureformat/Loader.h>
#include <logs/Log.h>

namespace liba
{
namespace lib2d
{
namespace objects
{

ImageSequence::ImageSequence( const Param & param )
:	width( 0 ),
	height( 0 )
{
	hard::Manager::add_dependent( this );
}

void ImageSequence::load( const ImageSequence::Param & param )
{
	HardVector::iterator it = hard_vector.begin();
	for( ;it != hard_vector.end(); ++it )
		it->second->clear();

	int num_p = 1;

	while( true )
	{
		char buf[255];
		sprintf( buf, "%03d", num_p );

		AutoPtr< pictureformat::Loader > pl = new pictureformat::Loader( param.image_name + buf );
		while( !pl->is_ready() );
		if( !pl->is_valid() )
			break;

		height = pl->get_height();
		width = pl->get_width();
		HardVector::iterator it = hard_vector.begin();
		for( ;it != hard_vector.end(); ++it )
		{
			hard::Manager::hardware_type * hardware = it->first;
			pictureformat::Format hardware_format = hardware->get_associated_format( pl->get_best_format() );
			pl->reset( hardware_format );
			it->second->push_back( hardware->create_image( pl->get_width(), pl->get_height(), hardware_format ) );

			hard::Image * tex = it->second->back();
			int stride = 0;
			void * dst = tex->lock( &stride );
			dst = reinterpret_cast<char *>(dst) + (pl->get_height() - 1) * stride;
			for( int i = 0; i != pl->get_height(); ++i )
			{
				pl->unpack_scanline( dst );
				dst = reinterpret_cast<char *>(dst) - stride;
			}
			tex->unlock();
		}

		++num_p;
	}
	stop_loading();
}

void ImageSequence::on_add_hardware(hard::Manager::hardware_type * ha)
{
	hard_vector.push_back( SweetPair( ha, new std::vector< AutoPtr< hard::Image > > ) );
	start_loading();
}

} //namespace objects
} //namespace lib2d
} //namespace liba

